#!/bin/sh
VIP="$1"

UNICONF=unix:/tmp/uniconfd

log()
{
	echo "$@" >&2
}

usage()
{
	log "Usage: $0 <filename.vip>"
	log " Installs a .vip versabox installer package in a new team."
	exit 1
}

assert()
{
	if ! "$@"; then
		log "ASSERTION FAILURE: '$*'"
		exit 6
	fi
}

if [ -z "$VIP" ]; then
	usage
fi
if [ ! -e "$VIP" ]; then
	log "$VIP: no such file!"
	exit 2
fi
VIP="$(fullname "$VIP")"
if ! unzip -qq -t "$VIP" vip.ini; then
	log "$VIP: contains no vip.ini!"
	exit 2
fi

INIFILE=/tmp/vip.ini.$$
rm -f $INIFILE
unzip -qq -p "$VIP" vip.ini >$INIFILE

unset TEAM

NAME=$(UNICONF="ini:$INIFILE" uni get '/Versa Installer/Name' 'VersaBox')
UNICONF="ini:$INIFILE" uni get '/Versa Installer/Steps' \
 | while read cmd a b c d; do
 	[ -z "$cmd" ] && continue
 	log
	log "-- $cmd $a $b $c $d"
	case $cmd in
		team)
			assert [ "$a" != "$MYNAME" ]
			assert uni get /cfg/users
			if uni get "/cfg/addons/$a"; then
				log "Deleting old addon for '$a'"
				uni set "/cfg/addons/$a/enabled" 0
				wvkick
				uni del "/cfg/addons/$a"
				wvkick
			fi
			if uni get "/cfg/users/$a"; then
				log "Deleting old team '$a'"
				uni del "/cfg/groups/$a"
				uni del "/cfg/users/$a"
				wvkick
			fi
			assert [ ! -d "/VERSA/.home/$a" ]
			log "Creating team '$a'."
			uni set "/cfg/groups/$a" "$a"
			uni set "/cfg/full names/$a" "$NAME"
			wvkick
			assert [ -d "/VERSA/.home/$a/Files" ]
			TEAM="$a"
			;;
			
		ini) 
			assert unzip -qq -t "$VIP" "$a"
			unzip -qq -p "$VIP" "$a" >/tmp/initmp.$$
			unicopy ini:/tmp/initmp.$$ \
				"subtree:{$UNICONF} /cfg"
			;;
			
		extract)
			assert [ -z "$a" ]
			assert [ -n "$TEAM" ]
			if [ ! -e /versabox.tar.gz ]; then
				versa-repack-self
			fi
			assert [ -e /versabox.tar.gz ]
			assert [ -d "/VERSA/.home/$TEAM/Files/." ]
			(
				cd "/VERSA/.home/$TEAM/Files"
				tar -xzf /versabox.tar.gz
				assert [ -e "./filesystem" ]
				rm -f filesystem
				assert [ ! -e "./filesystem" ]
				versatar -xF "$VIP" -w .stamp
				assert [ -e "./filesystem" ]
			) || exit 7
			;;
			
		start)
			assert [ -n "$TEAM" ]
			(
				export UNICONF="subtree:{$UNICONF} /cfg/addons/$TEAM"
				uni set "enabled" 0
				uni set "name" "$NAME"
				uni set "no context" 1
				uni set "start prog" "$a"
				uni set "enabled" 1
			)
			wvkick
			;;
		
		*)	log "Unknown command ($cmd)!!"
			exit 5
			;;
	esac
done || exit $?

exit 0
